﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Data;
using System.Data.SqlClient;
using System.Configuration;

namespace QuanLySuKien.model
{
    public class DataAccess
    {

        string connectionString = ConfigurationManager.ConnectionStrings["SukienConnection"].ConnectionString;
        SqlConnection con = null;

        public DataAccess()
        {
            con = new SqlConnection(connectionString);
        }

        public object GetScalar(string sql)
        {           
            try
            {
                con.Open();
                using (con)
                {
                    DataTable dt = new DataTable();
                    SqlCommand cmd = new SqlCommand(sql, con);
                    return cmd.ExecuteScalar();
                }
            }
            catch (Exception ex)
            {
                Console.WriteLine("Error:" + ex);
                return null;
            }
        }

        public DataTable Select(string sql)
        {
            try
            {
                con.Open();
                using (con)
                {
                    DataTable dt = new DataTable();
                    SqlCommand cmd = new SqlCommand(sql, con);
                    SqlDataAdapter da = new SqlDataAdapter(cmd);
                    da.Fill(dt);
                    return dt;
                }
            }
            catch (Exception ex)
            {
                Console.WriteLine("Error:" + ex);
                return null;
            }
        }

        public int InsertUpdate(string sql)
        {
            try
            {
                con.Open();
                using (con)
                {
                    SqlCommand cmd = new SqlCommand(sql, con);
                    cmd.CommandText = sql;
                    return cmd.ExecuteNonQuery();
                }
            }
            catch (Exception ex)
            {
                Console.WriteLine("Error:" + ex);
                return 0;
            }
        }
    }    
}